package org.netty.server.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;
import org.netty.protocol.file.*;
import org.netty.utils.ProtocolUtils;
import org.netty.utils.file.CacheUtil;
import org.netty.utils.file.FileUtil;
import org.netty.utils.file.MsgUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ServerHandler extends ChannelInboundHandlerAdapter {
    private final Logger logger = Logger.getLogger(this.getClass());

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof List) {
            logger.debug("这是一个List:" + msg);
        } else if (msg instanceof Map) {
            logger.debug("这是一个Map:" + msg);
        } else {
            logger.debug("这是一个对象：" + msg);
            //数据格式验证
            if ((msg instanceof FileTransferProtocol)) {

                FileTransferProtocol fileTransferProtocol = (FileTransferProtocol) msg;
                //0传输文件'请求'、1文件传输'指令'、2文件传输'数据'
                switch (fileTransferProtocol.getTransferType()) {
                    case 0:
                        FileDescInfo fileDescInfo = (FileDescInfo) fileTransferProtocol.getTransferObj();

                        //断点续传信息，实际应用中需要将断点续传信息保存到数据库中
                        FileBurstInstruct fileBurstInstructOld = CacheUtil.burstDataMap.get(fileDescInfo.getFileName());
                        if (null != fileBurstInstructOld) {
                            if (fileBurstInstructOld.getStatus() == Constants.FileStatus.COMPLETE) {
                                CacheUtil.burstDataMap.remove(fileDescInfo.getFileName());
                            }
                            //传输完成删除断点信息
                            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 服务端，接收客户端传输文件请求[断点续传]。" +
                                    "文件名：" + fileBurstInstructOld.getClientFileUrl() + "读取位置：" + fileBurstInstructOld.getReadPosition());
                            ctx.writeAndFlush(ProtocolUtils.prtclInstance(MsgUtil.buildTransferInstruct(fileBurstInstructOld)));
                            return;
                        }

                        //发送信息
                        FileTransferProtocol sendFileTransferProtocol = MsgUtil.buildTransferInstruct(Constants.FileStatus.BEGIN, fileDescInfo.getFileUrl(), 0L);
                        ctx.writeAndFlush(ProtocolUtils.prtclInstance(sendFileTransferProtocol));
                        logger.debug(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 服务端，接收客户端传输文件请求。开始读取文件");
                        break;
                    case 2:
                        FileBurstData fileBurstData = (FileBurstData) fileTransferProtocol.getTransferObj();
                        FileBurstInstruct fileBurstInstruct = FileUtil.writeFile("D://", fileBurstData);

                        //保存断点续传信息
                        CacheUtil.burstDataMap.put(fileBurstData.getFileName(), fileBurstInstruct);

                        ctx.writeAndFlush(ProtocolUtils.prtclInstance(MsgUtil.buildTransferInstruct(fileBurstInstruct)));
                        logger.debug(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 服务端，接收客户端传输文件请求。" +
                                "文件名：" + fileBurstData.getFileUrl() + "读取位置：" + fileBurstInstruct.getReadPosition());
                        //传输完成删除断点信息
                        if (fileBurstInstruct.getStatus() == Constants.FileStatus.COMPLETE) {
                            CacheUtil.burstDataMap.remove(fileBurstData.getFileName());
                            System.out.println("接收完成");
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }
}
